﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Zhongy
{
    public class MsgRecord
    {
        private Dictionary<string, SocketSendMsg> dicID2Msg = new Dictionary<string, SocketSendMsg>();
        private Dictionary<string, long> dicID2Time = new Dictionary<string, long>();

        private int updateTimerId = -1;
        public MsgRecord()
        {
        }

        private IList<int> needRecordLst = new List<int>()
        {
            //OpCode.TYPE_ACK2C,
            OpCode.TYPE_GAME_DISCONNECT,
            OpCode.TYPE_STOP_GAME_G,
        };
        public bool IsExsit(string msgId)
        {
            return dicID2Msg.ContainsKey(msgId);
        }

        public SocketSendMsg Get(string msgId)
        {
            if (IsExsit(msgId))
                return dicID2Msg[msgId];

            return null;
        }

        public void Add(SocketSendMsg msg)
        {
            if (updateTimerId == -1)
            {
                updateTimerId = TimerManager.Instance.AddFixedTimer(1, CheckValid, null, 1 * 1000);
            }
            
            if (!needRecordLst.Contains(msg.MT))
                return;

            if (msg == null || string.IsNullOrEmpty(msg.mesgid) || IsExsit(msg.mesgid))
            {
                Debug.Log("<color=red>消息id为空或重复</color>");
                return;
            }

            dicID2Msg[msg.mesgid] = msg;

            dicID2Time[msg.mesgid] = EncodeTool.GetTimestamp(DateTime.Now);
        }

        public void Sub(string msgId)
        {
            if (IsExsit(msgId))
            {
                dicID2Msg.Remove(msgId);
                dicID2Time.Remove(msgId);
            }
        }


        void CheckValid()
        {
            if(dicID2Time.Count <=0)
                return;

            IList<string> removeLst = new List<string>();

            foreach (KeyValuePair<string,long> item in dicID2Time)
            {
                DateTime dt = EncodeTool.NewDate(item.Value);
                if ((DateTime.Now - dt).TotalSeconds > 5)
                {
                    removeLst.Add(item.Key);
                }
            }

            foreach (string key in removeLst)
            {
                Sub(key);
            }
        }

    }
}
